﻿using Bottle.CommunityForum.Common;
using Bottle.CommunityForum.Factory;
using Bottle.CommunityForum.IBLL;
using Bottle.CommunityForum.Model;
using Bottle.CommunityForum.Model.Param;
using Bottle.CommunityForum.UIPortal.Models;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Bottle.CommunityForum.UIPortal.Controllers
{
    public class AdminHomeController : BaseController
    {
        //
        // GET: /AdminHoem/

        public IUserInfoService UserServcie
        {
            get { return StaticBLLFactory.GetCurrentUserInfoService(); }
        }

        public IRoleInfoService RoleServcie
        {
            get { return StaticBLLFactory.GetCurrentRoleInfoService(); }
        }

        public INodesInfoService NodesServcie
        {
            get { return StaticBLLFactory.GetCurrentNodesInfoService(); }
        }

        public IPageInfoService PageServcie
        {
            get { return StaticBLLFactory.GetCurrentPageInfoService(); }
        }

        public ActionResult Index()
        {
            return View();
        }

        /// <summary>
        /// 后台登录头部信息
        /// </summary>
        /// <returns></returns>
        public PartialViewResult HeaderERPLogIn()
        {
            UserViewModel userModel = JsonConvert.DeserializeObject<UserViewModel>(AspFormsAuthentication.getUserInfo());
            return PartialView("_HeaderERPLogIn", userModel);
        }

        #region 用户操作

        
        /// <summary>
        /// 用户管理
        /// </summary>
        /// <returns></returns>
        public ActionResult UserIndex()
        {
            if (!IsLogin)
            {
                return RedirectToAction("Index", "Home");
            }
            return PartialView();
        }

        /// <summary>
        /// 获取用户列表
        /// </summary>
        /// <returns></returns>
        public ActionResult QueryUserInfoList()
        {
            //获取当前页码默认1
            int pageIndex = int.Parse(Request["page"] ?? "1");
            //获取显示条数默认10
            int pageSize = int.Parse(Request["limit"] ?? "10");

            string txtKey = Request["Key[id]"];

            var queryParam = new UserInfoParam()
            {
                pageIndex = pageIndex,
                pageSize = pageSize,
                totle = 0,
                isOrder = true,
                Keyword = txtKey
            };
            var pageData = UserServcie.QueryWhereLoadPage(queryParam, u => u.userid);

            var temp = pageData.Select(u => new
            {
                userid = u.userid,
                username = u.username,
                userpwd = u.userpwd,
                email = u.email,
                gender = u.gender,
                state = u.state
            });

            //var pageData = UserServcie.QueryPageOrdEntitys(pageSize, pageIndex, out totle, u => true, u => u.userid)
            //    .Select(u=>new {userid=u.userid,username=u.username,userpwd=u.userpwd, email = u.email, gender = u.gender, state = u.state });
            //转换成layer能接收的数据格式
            var data = new { code = delSuccess, msg = "success", count = queryParam.totle, data = temp.ToList() };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        #region 用户crud

        public ActionResult UserAdd()
        {
            ViewBag.RoleList = RoleServcie.QueryEntitys(r => true).ToList();
            return View();
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UserAdd(UserInfo model)
        {
            string[] roles = Request["roles"].ToString().Split(',');
            if (!ModelState.IsValid)
            {
                return Json(new { code = delError, msg = "身份验证失败！" });
            }
            List<int> roleList = new List<int>();
            for (int i = 0; i < roles.Length; i++)
            {
                roleList.Add(int.Parse(roles[i]));
            }
            var roleAll = RoleServcie.QueryEntitys(r => roleList.Contains(r.roleid));
            foreach (var role in roleAll)
            {
                model.role.Add(role);
            }
            var userInfo = UserServcie.AddEntity(model).userid;
            return Json(new { code = delSuccess, msg = "添加成功", data = userInfo });
        }

        public ActionResult UserEdit(int id = 0)
        {
            if (id == 0)
            {
                return Content("编号不存在！");
            }
            var userModel = UserServcie.QueryEntitys(u => u.userid == id)
                    .FirstOrDefault();

            ViewBag.RoleList = RoleServcie.QueryEntitys(r => true).ToList();

            return View(userModel);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UserEdit(UserInfo model)
        {
            string[] roles = Request["roles"].ToString().Split(',');
            if (!ModelState.IsValid)
            {
                return Json(new { code = delError, msg = "身份验证失败！" });
            }
            List<int> roleList = new List<int>();
            for (int i = 0; i < roles.Length; i++)
            {
                roleList.Add(int.Parse(roles[i]));
            }
            //var UserModel = UserServcie.QueryEntitys(u => u.userid == model.userid).FirstOrDefault();
            //UserModel.username = model.username;
            //UserModel.userpwd = model.userpwd;
            //UserModel.email = model.email;
            //var roleAll = RoleServcie.QueryEntitys(r => roleList.Contains(r.roleid));
            //UserModel.role.Clear();
            //foreach (var role in roleAll)
            //{
            //    UserModel.role.Add(role);
            //}
            bool isSuccess = UserServcie.SetRole(model,roleList);
            return Json(new { code = isSuccess ? delSuccess : delError, msg = isSuccess ? "修改成功！" : "修改失败", data = model });
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult UserDel(int id = 0)
        {
            if (id == 0)
            {
                return Json(new { code = delError, msg = "编号不存在！" });
            }
            var model = UserServcie.QueryEntitys(u => u.userid == id)
                    .FirstOrDefault();
            var roles = new List<RoleInfo>();
            roles.AddRange(model.role.Select(r => r));
            foreach (var role in roles)
            {
                model.role.Remove(role);
            }
            var userInfo = UserServcie.DelEntity(model);
            return Json(new { code = delSuccess, msg = "删除成功！", data = userInfo });
        }

        #endregion

        #endregion

        #region 角色操作


        /// <summary>
        /// 角色管理
        /// </summary>
        /// <returns></returns>
        public ActionResult RoleIndex()
        {
            if (!IsLogin)
            {
                return RedirectToAction("Index", "Home");
            }
            return View();
        }

        /// <summary>
        /// 获取角色列表
        /// </summary>
        /// <returns></returns>
        public ActionResult QueryRoleInfoList()
        {
            //获取当前页码默认1
            int pageIndex = int.Parse(Request["page"] ?? "1");
            //获取显示条数默认10
            int pageSize = int.Parse(Request["limit"] ?? "10");

            string txtKey = Request["Key[id]"];

            var queryParam = new RoleInfoParam()
            {
                pageIndex = pageIndex,
                pageSize = pageSize,
                totle = 0,
                isOrder = true,
                Keyword = txtKey
            };
            var pageData = RoleServcie.QueryWhereLoadPage(queryParam, r => r.roleid);

            var temp = pageData.Select(r => new
            {
                roleid = r.roleid,
                rolename = r.rolename,
                content = r.content
            });

            //var pageData = UserServcie.QueryPageOrdEntitys(pageSize, pageIndex, out totle, u => true, u => u.userid)
            //    .Select(u=>new {userid=u.userid,username=u.username,userpwd=u.userpwd, email = u.email, gender = u.gender, state = u.state });
            //转换成layer能接收的数据格式
            var data = new { code = delSuccess, msg = "success", count = queryParam.totle, data = temp.ToList() };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        #region 角色crud

        public ActionResult RoleAdd()
        {
            return View();
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult RoleAdd(RoleInfo model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new { code = delError, msg = "身份验证失败！" });
            }
            var roleInfo = RoleServcie.AddEntity(model);
            return Json(new { code = delSuccess, msg = "添加成功", data = roleInfo });
        }

        public ActionResult RoleEdit(int id = 0)
        {
            if (id == 0)
            {
                return Content("编号不存在！");
            }
            var roleModel = RoleServcie.QueryEntitys(r => r.roleid == id)
                    .FirstOrDefault();
            return View(roleModel);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult RoleEdit(RoleInfo model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new { code = delError, msg = "身份验证失败！" });
            }
            var roleInfo = RoleServcie.EditEntity(model);
            return Json(new { code = delSuccess, msg = "修改成功！", data = roleInfo });
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult RoleDel(int id = 0)
        {
            if (id == 0)
            {
                return Json(new { code = delError, msg = "编号不存在！" });
            }
            var model = RoleServcie.QueryEntitys(r => r.roleid == id)
                    .FirstOrDefault();
            var roleInfo = RoleServcie.DelEntity(model);
            return Json(new { code = delSuccess, msg = "删除成功！", data = roleInfo });
        }

        #endregion

        #endregion

        #region 节点操作


        /// <summary>
        /// 节点管理
        /// </summary>
        /// <returns></returns>
        public ActionResult NodesIndex()
        {
            if (!IsLogin)
            {
                return RedirectToAction("Index", "Home");
            }
            return View();
        }

        /// <summary>
        /// 获取节点列表
        /// </summary>
        /// <returns></returns>
        public ActionResult QueryNodesInfoList()
        {
            //获取当前页码默认1
            int pageIndex = int.Parse(Request["page"] ?? "1");
            //获取显示条数默认10
            int pageSize = int.Parse(Request["limit"] ?? "10");

            string txtKey = Request["Key[id]"];

            var queryParam = new NodesInfoParam()
            {
                pageIndex = pageIndex,
                pageSize = pageSize,
                totle = 0,
                isOrder = true,
                Keyword = txtKey
            };
            var pageData = NodesServcie.QueryWhereLoadPage(queryParam, n => n.nodesid);

            var temp = pageData.ToList().Select(n => new
            {
                nodesid = n.nodesid,
                nodesname = n.nodesname,
                nodesno = n.nodesno,
                keywords = n.keywords,
                content = n.content,
                parentNodeName = NodesServcie.QueryEntitys(n1 => n1.nodesid == n.parent).FirstOrDefault().nodesno,
                gourl = PageServcie.QueryEntitys(p => p.pageid == n.tb_pageid).FirstOrDefault().gourl
            });

            //var pageData = UserServcie.QueryPageOrdEntitys(pageSize, pageIndex, out totle, u => true, u => u.userid)
            //    .Select(u=>new {userid=u.userid,username=u.username,userpwd=u.userpwd, email = u.email, gender = u.gender, state = u.state });
            //转换成layer能接收的数据格式
            var data = new { code = delSuccess, msg = "success", count = queryParam.totle, data = temp.ToList() };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        #region 节点crud

        public ActionResult NodesAdd()
        {
            return View();
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult NodesAdd(NodesInfo model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new { code = delError, msg = "身份验证失败！" });
            }
            var roleInfo = NodesServcie.AddEntity(model);
            return Json(new { code = delSuccess, msg = "添加成功", data = roleInfo });
        }

        public ActionResult NodesEdit(int id = 0)
        {
            if (id == 0)
            {
                return Content("编号不存在！");
            }
            var roleModel = NodesServcie.QueryEntitys(n => n.nodesid == id)
                    .FirstOrDefault();
            return View(roleModel);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult NodesEdit(NodesInfo model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new { code = delError, msg = "身份验证失败！" });
            }
            var roleInfo = NodesServcie.EditEntity(model);
            return Json(new { code = delSuccess, msg = "修改成功！", data = roleInfo });
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult NodesDel(int id = 0)
        {
            if (id == 0)
            {
                return Json(new { code = delError, msg = "编号不存在！" });
            }
            var model = NodesServcie.QueryEntitys(n => n.nodesid == id)
                    .FirstOrDefault();
            var roleInfo = NodesServcie.DelEntity(model);
            return Json(new { code = delSuccess, msg = "删除成功！", data = roleInfo });
        }

        #endregion

        #endregion

        #region 页面操作


        /// <summary>
        /// 页面管理
        /// </summary>
        /// <returns></returns>
        public ActionResult PageIndex()
        {
            if (!IsLogin)
            {
                return RedirectToAction("Index", "Home");
            }
            return View();
        }

        /// <summary>
        /// 获取页面列表
        /// </summary>
        /// <returns></returns>
        public ActionResult QueryPageInfoList()
        {
            //获取当前页码默认1
            int pageIndex = int.Parse(Request["page"] ?? "1");
            //获取显示条数默认10
            int pageSize = int.Parse(Request["limit"] ?? "10");

            string txtKey = Request["Key[id]"];

            var queryParam = new PageInfoParam()
            {
                pageIndex = pageIndex,
                pageSize = pageSize,
                totle = 0,
                isOrder = true,
                Keyword = txtKey
            };
            var pageData = PageServcie.QueryWhereLoadPage(queryParam, p => p.pageid);

            var temp = pageData.Select(p => new
            {
                pageid = p.pageid,
                pagename =p.pagename,
                gourl = p.gourl,
                content =p.content
            });

            //var pageData = UserServcie.QueryPageOrdEntitys(pageSize, pageIndex, out totle, u => true, u => u.userid)
            //    .Select(u=>new {userid=u.userid,username=u.username,userpwd=u.userpwd, email = u.email, gender = u.gender, state = u.state });
            //转换成layer能接收的数据格式
            var data = new { code = delSuccess, msg = "success", count = queryParam.totle, data = temp.ToList() };
            return Json(data, JsonRequestBehavior.AllowGet);
        }

        #region 页面crud

        public ActionResult PageAdd()
        {
            return View();
        }

        /// <summary>
        /// 添加
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult PageAdd(PageInfo model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new { code = delError, msg = "身份验证失败！" });
            }
            var roleInfo = PageServcie.AddEntity(model);
            return Json(new { code = delSuccess, msg = "添加成功", data = roleInfo });
        }

        public ActionResult PageEdit(int id = 0)
        {
            if (id == 0)
            {
                return Content("编号不存在！");
            }
            var roleModel = PageServcie.QueryEntitys(p => p.pageid == id)
                    .FirstOrDefault();
            return View(roleModel);
        }

        /// <summary>
        /// 修改
        /// </summary>
        /// <param name="model"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult PageEdit(PageInfo model)
        {
            if (!ModelState.IsValid)
            {
                return Json(new { code = delError, msg = "身份验证失败！" });
            }
            var roleInfo = PageServcie.EditEntity(model);
            return Json(new { code = delSuccess, msg = "修改成功！", data = roleInfo });
        }

        /// <summary>
        /// 删除
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult PageDel(int id = 0)
        {
            if (id == 0)
            {
                return Json(new { code = delError, msg = "编号不存在！" });
            }
            var model = PageServcie.QueryEntitys(p => p.pageid == id)
                    .FirstOrDefault();
            var roleInfo = PageServcie.DelEntity(model);
            return Json(new { code = delSuccess, msg = "删除成功！", data = roleInfo });
        }

        #endregion

        #endregion
    }
}
